from celery_tasks.main import celery_app
from django.template import loader
from django.conf import settings
import os

from goods.utils import get_categories, get_goods_and_specs


@celery_app.task(name='generate_static_sku_detail_html')
def generate_static_sku_detail_html(sku_id):

    # =========2\获取动态数据==============
    categories = get_categories()

    # 代码有些多可以使用封装函数进行调用
    # sku = SKU.objects.get(id=sku_id)
    # # GOODS即SPU的对象,通过外键属性获取对象
    # goods = sku.goods
    # specs = None

    goods, sku, specs = get_goods_and_specs(sku_id)

    # ============1\先构建模板================
    # 构建模板参数
    context = {
        'categories': categories,   # 先调试可以使用None
        'goods': goods,
        'sku': sku,
        'specs': specs
    }
    # 获取模板
    template = loader.get_template('detail.html')
    # 渲染模板
    sku_html_text = template.render(context=context)
    # 写入模板
    file_path = os.path.join(settings.GENERATED_STATIC_HTML_FILES_DIR, 'goods/'
                             + str(sku_id) + '.html')

    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(sku_html_text)